import React, { Component } from 'react';
import { is } from 'immutable'
import { Input, Row, Col } from 'antd';
import {connect} from 'react-redux'
import { file_type_items, last_update_items } from './tab_result'
import { editor_input } from '../actions/search_action'

const Search = Input.Search;

const input_style = {
    marginBottom: 10
};

const title_style = {
    paddingBottom: 50,
    fontSize: 50,
    fontWeight: 'normal',
    fontFamily:'"Times New Roman",Georgia,"Sans-serif"'
}

export class InputComponent extends Component{

    componentDidMount() {

    }

    shouldComponentUpdate(nextProps, nextState){
        return !(this.props === nextProps || is(this.props, nextProps)) ||
            !(this.state === nextState || is(this.state, nextState));
    }

    render() {
        const { state, dispatch } = this.props;

        return (
            <div>
                <Row>
                    <Col offset={6}>
                        <h1 style={title_style}>Advanced Google Search</h1>
                    </Col>
                </Row>
                <Row>
                    <Col span={10} offset={6}>
                        <Search
                            size="large"
                            value={state.input.get('input_text')}
                            style={input_style}
                            onChange={(event)=>{
                                dispatch(editor_input(event.target.value))
                            }}
                            onSearch={(value) => {
                                requestGoogle(makeSearchUrl(state))
                            }}
                        />
                    </Col>
                </Row>
            </div>



        )

    }

}

/**
 * 在新窗口打开url
 * @param url
 */
function requestGoogle(url) {
    window.open(url, '_blank')
}

/**
 * 拼接搜索语句
 * @param state
 * @returns {string}
 */
export function makeSearchText(state) {
    let search_text = '';

    let operator_content = state.search_operator.get('content');

    //exact phrase
    let exact_list = operator_content.get('exact_match').get('list').valueSeq();
    exact_list = makeItemString(exact_list, (item)=>{
        return '"' + item + '"';
    })
    search_text = search_text + toString(exact_list);

    //subtract phrase
    let subtract_list = operator_content.get('subtract').get('list').valueSeq();
    subtract_list = makeItemString(subtract_list, (item)=>{
        return '-' + '"' + item + '"'
    })
    search_text = search_text + toString(subtract_list);

    //may phrase
    let may_list = operator_content.get('may').get('list').valueSeq();
    may_list = makeItemString(may_list, (item)=>{
        return '"' + item  + '"' + ' OR';
    })
    if (may_list.length == 1) {
        may_list[0] = may_list[0] + ' "' + ' "';
    } else if (may_list.length > 1) {
        var tmp = may_list[may_list.length-1];
        may_list[may_list.length-1] = tmp.replace(/\sOR$/, '');
    }
    search_text = search_text + toString(may_list);

    //synonyms phrase
    let synonyms_list = operator_content.get('synonyms').get('list').valueSeq();
    synonyms_list = makeItemString(synonyms_list, (item) => {
        return item.split(/\s+/).reduce((acc, cur)=>{
           return acc + ' ~' + cur;
        },'').replace(/^\s+|\s+$/, '')
    })
    search_text = search_text + toString(synonyms_list);

    //range phrase
    let range_from = operator_content.get('range').get('from');
    let range_to = operator_content.get('range').get('to');
    range_from = trim(range_from);
    range_to = trim(range_to);
    if(range_from && range_to) {
        search_text = search_text + ' ' + range_from + '..' + range_to;
    }


    let command_content = state.search_command.get('content');

    //site
    let site = command_content.get('site');
    site = trim(site);
    if(site)
        search_text = search_text + ' ' + 'site:' + site;

    //intitle
    let intitle_list = command_content.get('intitle').get('list').valueSeq();
    intitle_list = makeItemString(intitle_list, (item)=>{
        return 'intitle:' + '"' + item + '"';
    })
    search_text = search_text + toString(intitle_list);

    //inurl
    let inurl_list = command_content.get('inurl').get('list').valueSeq();
    inurl_list = makeItemString(inurl_list, (item)=>{
        return 'inurl:' + '"' + item + '"';
    })
    search_text = search_text + toString(inurl_list);

    //inanchor
    let inanchor_list = command_content.get('inanchor').get('list').valueSeq();
    inanchor_list = makeItemString(inanchor_list, (item)=>{
        return 'inanchor:' + '"' + item + '"';
    })
    search_text = search_text + toString(inanchor_list);

    //filetype
    let result_content = state.result_refine.get('content');
    let file_type_index = result_content.get('file_type');
    if(file_type_index != 0) {
        let file_type = file_type_items[file_type_index];
        (/\(\.(.*)\)/.test(file_type));
        file_type = RegExp.$1;
        search_text = search_text +  ' ' + 'filetype:' + file_type;
    }

    //input
    let input_text = state.input.get('input_text');
    input_text = trim(input_text);
    search_text = search_text + ' ' + input_text;

    //去掉首尾的空格
    search_text = search_text.replace(/(^\s)|(\s$)/g, '');

    return search_text;

    //将非引号内的空格都变成一个

    // //(^[^"].*?(?=("|$))） 匹配开头到引号 如 aa "bb" cc 匹配aa
    // /(^[^"].*?(?=("|$)))/.test(search_text);
    // let head = RegExp.$1;
    // head = head.replace(/\s+/, ' ');
    // search_text.replace(/(^[^"].*?(?=("|$)))/, head);
    //
    // /(.*"|^)(.*?[^"]$)/.test(search_text);
    // head = RegExp.$1;
    // let tail = RegExp.$2;
    // tail = tail.replace(/\s+/, ' ');
    // search_text = head + tail;

}

/**
 * 拼接请求的url
 * @param state
 * @returns {string}
 */
export function makeSearchUrl(state) {
    let query_text = makeSearchText(state);
    let search_url = 'https://www.google.com/search?' + 'q=' + query_text

    //last_update
    let result_content = state.result_refine.get('content');
    let last_update_index = result_content.get('last_update');
    if(last_update_index != '0') {
        let param = '';
        switch (last_update_index) {
            case '1':
                param = 'd';
                break;
            case '2':
                param = 'w';
                break;
            case '3':
                param = 'm';
                break;
            case '4':
                param = 'y';
                break;
            default:
                return search_url
        }
        return search_url + '&as_qdr=' + param;
    }
    return search_url;
}

function makeItemString(list, callback) {
    let new_arr = new Array();
    for (let i = 0; i < list.size; ++i) {
        var item = list.get(i);
        item = trim(item);
        if (item) {
            new_arr.push(callback(item))
        }
    }
    return new_arr;
}

function toString(list) {
    let result = '';
    for (let i = 0; i < list.length; ++i) {
        result = result + " " + list[i];
    }
    return result;
}

function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, '')
}

const mapStateToProps = (state) => {
    return {
        state: state
    }
};

const InputContainer = connect(
    mapStateToProps,
    null,
)(InputComponent);

export default InputContainer;